package cn.noodbabies.web.interceptor;

import cn.noodbabies.api.annotation.RequiredPermission;
import cn.noodbabies.api.domain.LoginInfo;
import cn.noodbabies.api.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器的配置
 * 用户需要登录才能进行系统
 *
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            //获取访问的方法
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //判断方法是否有RequiredPermission标签
            if(handlerMethod.hasMethodAnnotation(RequiredPermission.class)){
                //如果有，则需要登录才能进
                LoginInfo user = UserContext.getLoginUser();
                if(user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
